<?php
/**
 * 采购需求汇总表 demand_summary
 */
class SummaryHelper {
	
	static function getList($where=null, $s=0, $l=0, $order='quote_flow ASC,addtime DESC'){
		return Db::get('Summary')->select('t0.*, t1.name as user_name')
				->join('User')->on('t0.user_id=t1.id')
				->where($where)->limit($s, $l)->order($order)->getAll();
	}
	
	static function getCount($where=null){
		return Db::get('Summary')->count()->join('User')->on('t0.user_id=t1.id')->where($where)->getCol();
	}

	/**
	 * 取某采购需求的材料信息，材料总量求和
	 * 只取未设置供应商的材料
	 */
	static function getWares($summary_id, $all=0){
		return Db::get('SummaryItems')->select('*, SUM(amount) AS amount')
				->where(array('summary_id'=>$summary_id), $all?null:array('supplier_id','IS','NULL') )
				->order('sno')->group('ware_id')->hkey('ware_id')->getAll();
	}

	/**
	 * 添加定价
	 */
	static function quoteWares($summary_id, $offers){
       
	 	
            foreach($offers as $wareid=>&$row)
            {
                    $tmp = SupplierQuote::get($row[0], $wareid);
                    if(!$tmp || !floatval($tmp['quote'])){
                            Show::warn('请确认所有材料均选择有报价的供应商');
                    }
                    $row[2] = $tmp['quote'];
                    unset($row);
            }

		$items = Db::get('_DemandItems');
		$items->trans()->on();
		//$total	= 0.0;
		foreach($offers as $wareid=>$row)
		{
			list($suplid, $amount, $quote, $remark) = $row;
			$r = $items->update(array(
							'supplier_id'	=> $suplid,
							'price'			=> $quote,
							'quote_time'	=> time(),
							'state'			=> DemandItems::STATE_QUOTE,
							'quote_remark'		=> $remark
						))->where(array('summary_id'=>$summary_id, 'ware_id'=>$wareid))->exec();
			//$total	+= floatval($quote)*intval($amount);	// row total = amount * price
			if(!$r){
				$items->trans()->rollback();
				Show::warn('保存定价失败');
			}

                       
                                                                       
                }
		$items->trans()->commit();
		
		/**
		 * 检查汇总明细是否都有报价，有则修改汇总表状态
		 */
		if(!self::getWares($summary_id)){
			Summary::update($summary_id, array('quote_flow'=>1));
		}

		return true;
	}

	static function state2txt($summary_item_state){
		static $sets = array(0=>'初始状态', 1=>'汇总需求', 2=>'录入报价', 3=>'进入采购', 9=>'无法采购');
		return fetch_a_char($summary_item_state, $sets);
	}

	static function flow2text($flow){
		static $sets = array(0=>'可生成',1=>'全部生成');
		return fetch_a_char($flow, $sets);
	}

	
}
?>
